import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bilibili/util/view_util.dart';
import 'package:video_player/video_player.dart';

class VideoPlayer extends StatefulWidget {
  final String url;
  final String cover;
  final bool autoPlay;
  final bool looping;
  final double aspectRatio;
  final Widget? overlayUI;

  const VideoPlayer(
    this.url, {
    super.key,
    required this.cover,
    this.autoPlay = false,
    this.looping = false,
    this.aspectRatio = 16 / 9,
    this.overlayUI,
  });

  @override
  State<VideoPlayer> createState() => _VideoPlayerState();
}

class _VideoPlayerState extends State<VideoPlayer> {
  late VideoPlayerController
      _videoPlayerController; // video_player播放器controller
  late ChewieController _chewieController; //chevie播放器controller

  get _placeholder => FractionallySizedBox(
        widthFactor: 1,
        heightFactor: 1,
        child: cachedImage(widget.cover),
      );

  @override
  void initState() {
    super.initState();
    _videoPlayerController =
        VideoPlayerController.networkUrl(Uri.parse(widget.url));
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: widget.aspectRatio,
      autoPlay: widget.autoPlay,
      looping: widget.looping,
      placeholder: _placeholder,

      /// todo：自定义overlay层级不对，无法点击按钮
      overlay: widget.overlayUI,
      // showControls: false, // 关闭默认的控制器
      showOptions: false, // 关闭默认右上角的更多
    );
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double playerHeight = screenWidth / widget.aspectRatio;
    return Container(
      width: screenWidth,
      height: playerHeight,
      color: Colors.grey,
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }
}
